package com.licq.ldoc.writer.visitor.example.exampler;

import java.lang.reflect.Field;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;

import com.licq.ldoc.domain.AttributeType;
import com.licq.ldoc.utils.BeanUtils;
import com.licq.ldoc.writer.visitor.example.Exampler;

/**
 * 
 * @author liujian
 *
 */
public class BasicAttributeExampler extends Exampler {
	private static transient Log logger = LogFactory.getLog(BasicAttributeExampler.class);
	
	private org.dom4j.Element element;
	
	private Object object;
	
	private String property;
	
	private Object value;
	
	private AttributeType type;
	
	private boolean required;
	
	public BasicAttributeExampler(org.dom4j.Element element, Object object, String name, AttributeType type, 
			boolean required) {
		this(element, object, name, getPropertyValue(object, name), type, required);
	}
	
	public BasicAttributeExampler(org.dom4j.Element element, Object object, String name, Object value,
			AttributeType type, boolean required) {
		Assert.notNull(element, "element cannot be null.");
		Assert.hasText(name, "name must not be blank.");
		Assert.notNull(type, "type cannot be null.");
		this.element = element;
		this.object = object;
		this.property = name;
		this.value = value;
		this.type = type;
		this.required = required;
	}

	@Override
	public void create() {
		String propertyValue = getPropertyInString();
		if (propertyValue != null) {
			element.addAttribute(property, propertyValue);
		}
	}
	
	private String getPropertyInString() {
		if (value != null) {
			return type.toString(value);
		} else if (required) {
			return getDefaultPropertyValue(type);
		} else {
			return null;
		}
	}
	
	@Override
	protected String getDefaultEnumPropValue() {
		try {
			Field enumField = BeanUtils.getDeclaredField(object.getClass(), property);
			return enumField.getType().getEnumConstants()[0].toString();
		} catch (NoSuchFieldException e) {
			if (logger.isInfoEnabled()) {
				logger.info(String.format("no enum field[%s] in class[%s].", 
						property,
						object.getClass().getName()
					)
				);
			}
			return null;
		}
	}

	public static void main(String[] args) throws Exception {
		
	}

}
